import socket
import time
from common.loger_handler import mylog
from common.conf_handle import myconf

id = myconf.get("mount", "id")      # 相机ID

class MyClass:
    """UDP通信协议"""

    def __init__(self):
        # 设置目标地址和端口
        self.target_ip = '145.192.1.64'
        self.target_port = 7894
        # 绑定本地地址和端口
        self.local_ip = '0.0.0.0'
        self.local_port = 8085
        # 创建UDP套接字
        sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
        # 绑定本地地址和端口
        sock.bind((self.local_ip, self.local_port))
        print("UDP连接成功")
        self.socks = sock
        self.udp_sendto(F"FE 55 00 00 04 01 01 00 0A 00 02 0E 04 01 00 00 00 00 04 01 01 55 00 00 00 00 A7 DF")  # 连接配对
        time.sleep(3)

    def udp_sendto(self, message_a):
        """发送报文"""
        message = message_a.replace(" ", "")
        message_bytes = bytes.fromhex(message)
        self.socks.sendto(message_bytes, (self.target_ip, self.target_port))
        mylog.info(F"发送数据：{message_a}")

    def udp_receive(self, msgid,outtimes=3):
        """获取上报数据，输入msgid 例如：0001"""
        msg_list = []
        tag = 1  # 控制大循环
        lcoal = time.time()  # 控制超时时间
        self.socks.settimeout(outtimes)
        print("=================开始获取数据===========================")
        while bool(tag):
            # 接收数据
            try:
                data, addr = self.socks.recvfrom(1024)
                received_message = ' '.join([hex(byte)[2:].zfill(2) for byte in data])
                if F"fe 55 01 03 {id} 04 01 {msgid[2:]} {msgid[:2]}" in received_message:
                    msg_list.append(received_message)
                    # print(received_message)
            except BaseException:
                pass
            if time.time() - lcoal >= outtimes:  # 超时关闭上报
                mylog.info(F"UDP接收结束")
                break
        del msg_list[-1]
        return msg_list

    def udp_receive_all(self,outtimes=3):
        """获取上报数据，输入msgid 例如：0001"""
        msg_list = []
        tag = 1  # 控制大循环
        lcoal = time.time()  # 控制超时时间
        self.socks.settimeout(outtimes)
        print("=================开始获取数据===========================")
        while bool(tag):
            # 接收数据
            try:
                data, addr = self.socks.recvfrom(10240)
                received_message = ' '.join([hex(byte)[2:].zfill(2) for byte in data])
                if F"fe 55" in received_message:
                    msg_list.append(received_message)
                    # print(received_message)
            except BaseException:
                pass
            if time.time() - lcoal >= outtimes:  # 超时关闭上报
                mylog.info(F"UDP接收结束")
                break
        del msg_list[-1]
        return msg_list

    def udp_close(self):
        """主动断开UDP连接"""
        self.socks.close()
        mylog.info("****UDP断开连接****")


if __name__ == "__main__":
    G = MyClass()
    x = G.udp_receive_all(10)
    # x = G.udp_receive("0001")
    print(x)